<?php
namespace app\admin\controller\communityautoplan;

use app\common\controller\Backend;
use think\Db;
use fast\Tree;
include_once APP_PATH . 'api/common.php';

/**
 * 社区课程管理
 *
 * @icon fa fa-calendar
 */
class Communityautoplan extends Backend
{

    /**
     * Communityautoplan模型对象
     */
    protected $model = null;
    protected $multiFields = 'status';
    protected $noNeedRight = ["lists","getClockStatsAjax"];
    protected $noNeedLogin = ["lists", "getClockStatsAjax"];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Autoplan');
        $this->modelValidate = true;

        // 获取社区列表
        $communityList = Db::name('community')
            ->where('status', 1)
            ->field('id,name')
            ->order('id desc')
            ->select();

        // 获取教学点列表
        $ocationList = Db::name('ocation')
            ->where('status', 1)
            ->field('id,name')
            ->order('id desc')
            ->select();

        // 获取项目列表
        $projectList = Db::name('course_table')
            ->where('status', 1)
            ->field('id,name')
            ->order('id desc')
            ->select();

        if ($this->view !== null) {
            $this->view->assign('communityList', $communityList);
            $this->view->assign('ocationList', $ocationList);
            $this->view->assign('projectList', $projectList);
        }
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $user=$this->auth->getUserInfo();
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // 添加社区过滤逻辑
            $communityId = $this->request->get('community_id');
            $ocationId = $this->request->get('ocation_id');
            $projectId = $this->request->get('project_id');

            // 创建额外的查询条件数组
            $extraWhere = [];

            // 根据用户组进行数据过滤
            $admin = $_SESSION['think']['admin'] ?? [];
            if (isset($admin['group_id'])) {
                if ($admin['group_id'] == 8) { // 社区管理用户
                    if (isset($admin['community_id']) && !empty($admin['community_id'])) {
                        //$extraWhere[] = ['community_id', '=', $admin['community_id']];
                    }
                }
            }

            // 前端筛选条件
            if (!empty($communityId)) {
                //$extraWhere[] = ['community_id', '=', $communityId];
            }
            if (!empty($ocationId)) {
                $extraWhere[] = ['ocation_id', '=', $ocationId];
            }
            if (!empty($projectId)) {
                $extraWhere[] = ['project_id', '=', $projectId];
            }
            // 构建查询条件
            $query = $this->model->where($where)->where("table_type", '=', 2);
            $query->where("ocation_id", '=', $user['ocation_id']);
            // 添加额外的查询条件
            foreach ($extraWhere as $condition) {
                $query->where($condition[0], $condition[1], $condition[2]);
            }
            $total = $query->count();

            // 重新构建查询用于获取数据列表
            $list = $this->model->where($where)->where("table_type", '=', 2);

            // 添加额外的查询条件
            foreach ($extraWhere as $condition) {
                $list->where($condition[0], $condition[1], $condition[2]);
            }
            $list->where("ocation_id", '=', $user['ocation_id']);
            $list = $list->order("weigh asc");

            // 只有当排序字段不是 weigh 时，才添加额外的排序
            if ($sort != 'weigh') {
                $list = $list->order($sort, $order);
            }

            $list = $list->limit($offset, $limit)
                ->select();

            $list = collection($list)->toArray();
            for($i=0;$i<count($list);$i++){
                // 初始化courseConfig变量
                $courseConfig = null;

                // 课程名称（通过subject_lv关联fa_community_course_config表获取）
                if (!empty($list[$i]['subject_lv'])) {
                    $courseConfig = Db::name('community_course_config')->where('id', $list[$i]['subject_lv'])->find();
                    $list[$i]['course_name'] = $courseConfig ? $courseConfig['name'] : ($list[$i]['event_name'] ?? '');
                } else {
                    $list[$i]['course_name'] = $list[$i]['event_name'] ?? '';
                }

                // 课程封面（使用event_image）
                $list[$i]['course_cover'] = $courseConfig ? $courseConfig['cover'] : ($list[$i]['event_image'] ?? '');
                $list[$i]['course_cover'] = getImg($list[$i]['course_cover'],200,200);
                // 课程内容（使用event_content）
                $list[$i]['course_content'] = $list[$i]['event_content'] ?? '';

                // 课程类型映射（使用table_type字段）
                $courseTypeMap = [
                    1 => '公益活动',
                    2 => '社区活动',
                    3 => '研学活动',
                    4 => '趣味活动'
                ];
                $list[$i]['course_type'] = isset($courseTypeMap[$list[$i]['table_type']]) ? $courseTypeMap[$list[$i]['table_type']] : '社区活动';

                // 课堂类型（仅社区课堂）
                $list[$i]['class_type'] = '社区课堂';

                // 获取教学点名称
                $ocation = Db::name('ocation')->where('id', $list[$i]['ocation_id'])->find();
                $list[$i]['teaching_point'] = $ocation ? $ocation['name'] : '';

                // 上课地点（使用address字段）
                $list[$i]['class_address'] = $list[$i]['address'] ?? '';

                // 课程日期和时间
                $list[$i]['course_date'] = $list[$i]['date'] ?? '';
                $list[$i]['course_time'] = ($list[$i]['start_time'] ?? '') . '-' . ($list[$i]['end_time'] ?? '');

                $list[$i]['corver'] = getImg($list[$i]['event_image'],200,200);
            }
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        $user=$this->auth->getUserInfo();
        $ocation=Db::name('ocation')->where('id',$user['ocation_id'])->find();
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validate($validate);
                    }

                    // 验证日期限制
                    if (isset($params['date']) && !empty($params['date'])) {
                        // 获取日期限制配置
                        $restrictionType = $this->request->post('date_restriction', '');
                        $restrictionConfig = [];
                        
                        if ($restrictionType === 'custom_weekdays') {
                            $weekdays = $this->request->post('weekdays/a', []);
                            if (!empty($weekdays)) {
                                $restrictionConfig['weekdays'] = array_map('intval', $weekdays);
                            }
                        } elseif ($restrictionType === 'specific_dates') {
                            $specificDates = $this->request->post('specific_dates', '');
                            if (!empty($specificDates)) {
                                $dates = array_filter(array_map('trim', explode("\n", $specificDates)));
                                $restrictionConfig['dates'] = $dates;
                            }
                        }
                        
                        // 设置临时数据进行验证
                        $tempData = [
                            'date_restriction' => $restrictionType,
                            'restriction_config' => json_encode($restrictionConfig, JSON_UNESCAPED_UNICODE)
                        ];
                        
                        $validationResult = $this->model->validateDateRestriction($params['date'], $tempData);
                        if (!$validationResult['valid']) {
                            $this->error('日期验证失败：' . $validationResult['message']);
                        }
                        
                        // 将日期限制配置保存到参数中
                        $params['date_restriction'] = $restrictionType;
                        $params['restriction_config'] = $restrictionConfig;
                    }

                    unset($params['id']);
                    $params['status'] = isset($params['status']) ? $params['status'] : 1;
                    $params['create_time'] = time();
                    $params['table_type'] = 2;
                    $params['ocation_id']  = $user['ocation_id'];

                        // 自动插入session中的社区ID
                    $admin = $_SESSION['think']['admin'] ?? [];
                    if (isset($admin['group_id']) && $admin['group_id'] == 8) {
                        if (isset($admin['community_id']) && !empty($admin['community_id'])) {
                            $params['community_id'] = $admin['community_id'];
                        }
                    }

                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign([
            'user' => $user,
            'ocation' => $ocation,
        ]);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $user=$this->auth->getUserInfo();
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                // 省市取user的ocation_id的省市
                $params['ocation_id']  = $user['ocation_id'];
                $ocation=Db::name('ocation')->where('id',$user['ocation_id'])->find();
                $params['province_id'] = $ocation['province_id'];
                $params['city_id'] = $ocation['city_id'];

                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        //$row->validate($validate);
                    }

                    // 验证日期限制
                    if (isset($params['date']) && !empty($params['date'])) {
                        // 获取日期限制配置
                        $restrictionType = $this->request->post('date_restriction', $row['date_restriction'] ?? '');
                        $restrictionConfig = [];
                        
                        if ($restrictionType === 'custom_weekdays') {
                            $weekdays = $this->request->post('weekdays/a', []);
                            if (!empty($weekdays)) {
                                $restrictionConfig['weekdays'] = array_map('intval', $weekdays);
                            }
                        } elseif ($restrictionType === 'specific_dates') {
                            $specificDates = $this->request->post('specific_dates', '');
                            if (!empty($specificDates)) {
                                $dates = array_filter(array_map('trim', explode("\n", $specificDates)));
                                $restrictionConfig['dates'] = $dates;
                            }
                        }

                        
                        // 设置临时数据进行验证
                        $tempData = [
                            'date_restriction' => $restrictionType,
                            'restriction_config' => json_encode($restrictionConfig, JSON_UNESCAPED_UNICODE)
                        ];
                        
                        $validationResult = $this->model->validateDateRestriction($params['date'], $tempData);
                        if (!$validationResult['valid']) {
                            $this->error('日期验证失败：' . $validationResult['message']);
                        }
                        
                        // 将日期限制配置保存到参数中
                        $params['date_restriction'] = $restrictionType;
                        $params['restriction_config'] = $restrictionConfig;
                    }

                    // 处理新字段
                    if (isset($params['checkin_before_class'])) {
                        $params['checkin_before_class'] = intval($params['checkin_before_class']);
                    }
                    if (isset($params['checkin_after_class'])) {
                        $params['checkin_after_class'] = intval($params['checkin_after_class']);
                    }
                    if (isset($params['evaluation_after_class'])) {
                        $params['evaluation_after_class'] = intval($params['evaluation_after_class']);
                    }
                    if (isset($params['class_id'])) {
                        $params['class_id'] = intval($params['class_id']);
                    }
                    if (isset($params['admin_id'])) {
                        $params['admin_id'] = intval($params['admin_id']);
                    }
                    $params['ocation_id']  = $user['ocation_id'];

                    $params['update_time'] = time();
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        // 获取班级列表
        $classList = Db::name('ocation_class')
            ->where('status', 1)
            ->field('id,name')
            ->order('id desc')
            ->select();

        // 获取管理员列表
        $adminList = Db::name('admin')
            ->where('status', 'normal')
            ->field('id,nickname,username')
            ->order('id desc')
            ->select();

        // 获取打卡数据
        $clockData = $this->getClockData($ids, null, null, null, null);

        // 获取统计数据
        $stats = $this->calculateClockStats($ids, null, null, null, null);

        $this->view->assign("row", $row);
        $this->view->assign("classList", $classList);
        $this->view->assign("adminList", $adminList);
        $this->view->assign("clockData", $clockData);
        $this->view->assign("stats", $stats);
        return $this->view->fetch();
    }

    /**
     * 获取社区小组列表
     */
    public function getCommunityList()
    {
        $communityList = Db::name('community')->where('status', 1)->field('id,name')->select();
        $this->success('', '', $communityList);
    }

    /**
     * 获取可选择的课程日期
     */
    public function getAvailableDates()
    {
        // 获取当前用户信息
        $user = $this->auth->getUserInfo();
        $userGroupId = $user['group_id'] ?? 0;
        
        // 基础查询条件：状态为正常的课程日期
        $where = ['status' => 1];
        
        // 根据用户组进行数据过滤
        if ($userGroupId == 8) { // 社区管理用户
            if (isset($user['community_id']) && !empty($user['community_id'])) {
                $where['community_id'] = $user['community_id'];
            }
        } elseif ($userGroupId == 3) { // 学校管理用户
            if (isset($user['ocation_id']) && !empty($user['ocation_id'])) {
                $where['ocation_id'] = $user['ocation_id'];
            }
        }
        
        // 获取可选择的日期列表（未来30天内的有效日期）
        $startDate = date('Y-m-d');
        $endDate = date('Y-m-d', strtotime('+30 days'));
        
        $availableDates = Db::name('course_table_autoplan')
            ->where($where)
            ->where('date', '>=', $startDate)
            ->where('date', '<=', $endDate)
            ->where('status', 1)
            ->group('date')
            ->column('date');
            
        // 如果没有找到可用日期，返回默认的几个日期
        if (empty($availableDates)) {
            $availableDates = [
                date('Y-m-d', strtotime('+1 day')),
                date('Y-m-d', strtotime('+2 days')),
                date('Y-m-d', strtotime('+3 days'))
            ];
        }
        
        $this->success('', '', ['available_dates' => $availableDates]);
    }

    /**
     * 获取打卡统计数据
     */
    public function getClockStatsAjax()
    {
        // 从表单隐藏字段row[id]中获取课程ID
        $row = $this->request->post('row');
        $courseId = isset($row['id']) ? $row['id'] : $this->request->post('course_id');
        $startTime = $this->request->post('start_time');
        $endTime = $this->request->post('end_time');
        $communityId = $this->request->post('community_id');
        $courseType = $this->request->post('course_type');
        $currentClassOnly = $this->request->post('current_class_only', 0);

        if (!$courseId) {
            return json(['code' => 0, 'msg' => '课程ID不能为空']);
        }

        // 获取课程信息
        $courseInfo = $this->model->where('id', $courseId)->find();
        if (!$courseInfo) {
            return json(['code' => 0, 'msg' => '课程信息不存在']);
        }

        // 如果只查询当前课程，使用课程时间
        if ($currentClassOnly) {
            $startTime = $courseInfo['date'] . ' ' . $courseInfo['start_time'];
            $endTime = $courseInfo['date'] . ' ' . $courseInfo['end_time'];
        }

        // 统计上课人数（去重）
        $studentCount = Db::name('eb_class_student')
            ->where('classes_id', $courseInfo['classes_id'])
            ->where('status', 1)
            ->count();

        // 统计打卡次数（按类型分组）
        $clockStats = Db::name('user_clock')
            ->where('clock_time', 'between', [$startTime, $endTime])
            ->group('clock_type')
            ->column('COUNT(*)', 'clock_type');

        $checkinBefore = $clockStats[1] ?? 0; // 上课前打卡
        $checkinAfter = $clockStats[2] ?? 0; // 上课后打卡
        $evaluation = $clockStats[3] ?? 0; // 下课后评价

        // 统计请假人数
        $leaveCount = Db::name('user_leave')
            ->where('start_time', '<=', $startTime)
            ->where('end_time', '>=', $endTime)
            ->where('status', 1)
            ->count();

        // 课节数（当前课程就是1节）
        $classCount = 1;

        // 获取打卡数据
        $clockData = Db::name('user_clock')
            ->field('id,user_id,clock_time,clock_type,create_time')
            //->where('clock_time', 'between', [$startTime, $endTime])
            ->order('create_time desc')
            ->select();

        // 获取用户信息，添加到打卡数据中
        if (!empty($clockData)) {
            $userIds = array_unique(array_column($clockData, 'user_id'));
            $users = Db::name('user')
                ->where('id', 'in', $userIds)
                ->field('id,nickname,username,avatar')
                ->select();

            $userMap = [];
            foreach ($users as $user) {
                $userMap[$user['id']] = $user;
            }

            // 将用户信息添加到打卡数据中
            foreach ($clockData as &$clock) {
                $clock['user_info'] = $userMap[$clock['user_id']] ?? [];
            }
        }

        return json([
            'code' => 200,
            'data' => [
                'stats' => [
                    'student_count' => $studentCount,
                    'class_count' => $classCount,
                    'checkin_before' => $checkinBefore,
                    'checkin_after' => $checkinAfter,
                    'evaluation_count' => $evaluation,
                    'leave_count' => $leaveCount
                ],
                'clockData' => $clockData
            ]
        ]);
    }

    /**
     * 获取打卡统计数据（私有方法）
     */
    private function calculateClockStats($id, $startTime = null, $endTime = null, $communityId = null, $courseType = null)
    {
        // 如果没有指定时间范围，使用课程时间范围
        if (!$startTime || !$endTime) {
            $course = Db::name('course_table_autoplan')->where('id', $id)->find();
            if ($course) {
                $startTime = $course['date'] . ' ' . $course['start_time'];
                $endTime = $course['date'] . ' ' . $course['end_time'];
            } else {
                // 如果课程不存在，使用默认时间范围（今天）
                $startTime = date('Y-m-d 00:00:00');
                $endTime = date('Y-m-d 23:59:59');
            }
        }

        // 统计打卡数据
        $stats = [
            'student_count' => 0,      // 上课人数
            'class_count' => 1,        // 课节数
            'checkin_before' => 0,     // 上课前打卡次数
            'checkin_after' => 0,      // 上课后打卡次数
            'leave_count' => 0,        // 请假人数
            'evaluation_count' => 0    // 评价数
        ];

        // 获取打卡数据 - 使用字符串方式构建查询条件
        $clockData = Db::name('user_clock')
            ->where("clock_time >= '{$startTime}' AND clock_time <= '{$endTime}'")
            ->select();

        // 统计打卡类型
        foreach ($clockData as $item) {
            if ($item['clock_type'] == 1) {
                $stats['checkin_before']++;
            } elseif ($item['clock_type'] == 2) {
                $stats['checkin_after']++;
            } elseif ($item['clock_type'] == 3) {
                $stats['evaluation_count']++;
            }
        }

        // 统计上课人数（去重）
        $stats['student_count'] = Db::name('user_clock')
            ->where("clock_time >= '{$startTime}' AND clock_time <= '{$endTime}'")
            ->group('user_id')
            ->count();

        // 统计请假人数（假设请假记录在leave表中）
        $stats['leave_count'] = Db::name('user_leave')
            ->where("start_time <= '{$startTime}' AND end_time >= '{$endTime}'")
            ->where('status', 1)
            ->count();

        return $stats;
    }


    /**
     * 获取打卡数据
     */
    private function getClockData($id, $startTime = null, $endTime = null, $communityId = null, $courseType = null)
    {
        // 如果没有指定时间范围，使用课程时间范围
        $course_id=$this->request->post('course_id')??$id;
        if (!$startTime || !$endTime) {
            $course = Db::name('course_table_autoplan')->where('id', $course_id)->find();
            if ($course) {
                $startTime = $course['date'] . ' ' . $course['start_time'];
                $endTime = $course['date'] . ' ' . $course['end_time'];
            } else {
                // 如果课程不存在，使用默认时间范围（今天）
                $startTime = date('Y-m-d 00:00:00');
                $endTime = date('Y-m-d 23:59:59');
            }
        }

        // 获取打卡数据 - 使用字符串方式构建查询条件
        $clockData = Db::name('user_clock')
            ->where("clock_time >= '{$startTime}' AND clock_time <= '{$endTime}'")
            ->order('clock_time desc')
            ->select();

        // 关联用户信息
        foreach ($clockData as &$item) {
            $user = Db::name('user')->where('id', $item['user_id'])->find();
            $item['user_info'] = $user ? [
                'id' => $user['id'],
                'username' => $user['username'],
                'nickname' => $user['nickname'],
                'avatar' => $user['avatar']
            ] : [
                'id' => $item['user_id'],
                'username' => '未知用户',
                'nickname' => '未知用户',
                'avatar' => ''
            ];
        }

        return $clockData;
    }
    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (\PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 获取列表数据
     */
    public function lists()
    {
        $page = $this->request->get('page', 1);
        $pagesize = $this->request->get('pagesize', 10);
        $where = "where status=1";

        // 根据用户组进行数据过滤
        $admin = $_SESSION['think']['admin'] ?? [];
        if (isset($admin['group_id']) && $admin['group_id'] == 8) {
            if (isset($admin['community_id']) && !empty($admin['community_id'])) {
                $where .= " and community_id = " . $admin['community_id'];
            }
        }

        $sql = "select id,CONCAT(date,' ',start_time,'-',end_time) name from dev002_gxyusheng.fa_course_table_autoplan $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
        $list = db()->query($sql);

        $total = db()->query("select count(1) as c from dev002_gxyusheng.fa_course_table_autoplan $where")[0];

        return json(['list' => $list, 'total' => $total['c']]);
    }

    /**
     * 获取班级列表
     */
    public function getClasses()
    {
        $projectId = $this->request->get('project_id');
        $tableType = $this->request->get('table_type', 2); // 默认为社区班级

        if (!$projectId) {
            return json(['code' => 0, 'msg' => '项目ID不能为空']);
        }

        $where = [
            'project_id' => $projectId,
            'status' => 1
        ];

        // 根据班级类型选择不同的表
        if ($tableType == 1) {
            // 学校班级
            $classesList = Db::name('ocation_class')->where($where)->field('id,name')->select();
        } else {
            // 社区班级
            $classesList = Db::name('community_classes')->where($where)->field('id,name')->select();
        }

        return json(['code' => 1, 'data' => $classesList]);
    }
}